import os
import yaml
from common import get_parentdirectory
from pathlib import Path
class Yaml_Util():
    # 读取extract.yml文件所有内容
    def modify_testcase_extract(self, yaml_name, key,value):
        parentdirectory = get_parentdirectory.get_parent_directory()
        file_path = os.path.join(parentdirectory, 'testyml', yaml_name)
        # Read YAML data from file
        with open(file_path, mode='r', encoding='utf-8') as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
        for item in data:
            if key in item['data']:
                item['data'][key] = value
                print(f"修改后的 {key}: {item['data'][key]}")
            # Write modified YAML data back to file
            with open(file_path, mode='w', encoding='utf-8') as f:
                yaml.dump(data, f, allow_unicode=True)

    def read_testcase_yaml(self, yaml_name):
        # 处理绝对路径
        if Path(yaml_name).is_absolute():
            file_path = Path(yaml_name)
        else:
            parent_directory = Path(get_parentdirectory.get_parent_directory())
            print(parent_directory)
            # 拼接路径
            file_path = parent_directory / yaml_name

        # 检查文件是否存在
        if not file_path.exists():
            print(f"文件不存在: {file_path}")
            return None

        try:
            with open(file_path, mode='r', encoding='utf-8') as f:
                value = yaml.safe_load(f)
                return value
        except Exception as e:
            print(f"读取文件 {file_path} 时出错: {e}")
            return None

    def read_yaml(self,yaml_name):
        with open(yaml_name,mode='r',encoding='utf-8') as f:
            value = yaml.safe_load(f)
            # print(value)
            return value

    def clear_extract(self):
        file_path = os.path.join(os.getcwd(),'extract.yml')
        print(file_path)
        with open(file_path , mode='w', encoding='utf-8') as f:
            pass


if __name__ == '__main__':
    Yaml_Util().read_testcase_yaml('extract.yml')

